package com.simdo.g768.Fragment;

import static com.simdo.g768.MainActivity.device;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.TextView;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.simdo.g768.Adapter.WarningImsiAdapter;
import com.simdo.g768.Bean.ImsiBean;
import com.simdo.g768.Bean.MyUeidBean;
import com.simdo.g768.File.FileUtil;
import com.simdo.g768.Listener.BeanClickListener;
import com.simdo.g768.MainActivity;
import com.simdo.g768.R;
import com.simdo.g768.Util.AppLog;
import com.simdo.g768.Util.ExcelUtil;
import com.simdo.g768.Util.GsonUtil;
import com.simdo.g768.Util.PrefUtil;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

public class WarningChildFragment extends Fragment {

    Context mContext;
    private WarningImsiAdapter mImsiAdapter;
    private final List<ImsiBean> mImsiList = new ArrayList<>();
    public WarningChildFragment(Context context, List<ImsiBean> list) {
        this.mContext = context;
        this.mImsiList.addAll(list);
    }
    public WarningChildFragment() {
    }

    @SuppressLint("NotifyDataSetChanged")
    public void refreshListView() {
        if (!this.isVisible()) return;
        this.mImsiList.clear();
        for (ImsiBean bean : MainActivity.getInstance().getWarningImsiList()){
            if (bean.getImsi().contains(currentKey)) this.mImsiList.add(bean);
        }
        if (mImsiAdapter != null) mImsiAdapter.resetShowData();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AppLog.I("WarningChildFragment onCreate");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        AppLog.I("WarningChildFragment onCreateView");

        View root = inflater.inflate(R.layout.child_pager_warning, container, false);

        initView(root);
        return root;
    }

    @Override
    public void onResume() {
        super.onResume();
        AppLog.I("WarningChildFragment onCreateView");
        refreshListView();
    }

    private String currentKey = "";
    private void initView(View root) {
        EditText mEtSearch = root.findViewById(R.id.et_search);
        mEtSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void afterTextChanged(Editable s) {
                List<ImsiBean> mAllImsiList = MainActivity.getInstance().getWarningImsiList();
                currentKey = s.toString();
                mImsiList.clear();
                if (!TextUtils.isEmpty(s)){
                    for (ImsiBean bean : mAllImsiList){
                        if (bean.getImsi().contains(currentKey)) mImsiList.add(bean);
                    }
                } else mImsiList.addAll(mAllImsiList);
                mImsiAdapter.resetShowData();
            }
        });

        root.findViewById(R.id.iv_add).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showBlackListCfgDialog(true, null);
            }
        });
        root.findViewById(R.id.iv_import).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                //Uri uri = Uri.fromFile(new File(FileUtil.build().getSDPath()));
                //设置xls xlsx 2种类型 , 以 | 划分
                intent.setDataAndType(null, "application/vnd.ms-excel|application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                //在API>=19之后设置多个类型采用以下方式，setType不再支持多个类型
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    intent.putExtra(Intent.EXTRA_MIME_TYPES,
                            new String[]{"application/vnd.ms-excel", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
                } else {
                    intent.setType("application/vnd.ms-excel|application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                }
                activityForResult.launch(intent);
            }
        });
        root.findViewById(R.id.clear).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clear();
            }
        });
        // 列表
        RecyclerView rv_imsi_list = root.findViewById(R.id.rv_imsi_list);
        mImsiAdapter = new WarningImsiAdapter(mContext, mImsiList);
        mImsiAdapter.setOnItemClickListener(new BeanClickListener() {
            @Override
            public void onItemClickListener(View view, ImsiBean bean) {
                showBlackListCfgDialog(false, bean);
            }
        });
        rv_imsi_list.setLayoutManager(new LinearLayoutManager(mContext));
        rv_imsi_list.setAdapter(mImsiAdapter);
    }

    public void resetShowData(){
        if (mImsiAdapter != null) mImsiAdapter.resetShowData(); // 刷新视图
    }

    public void clear() {
        if (!mImsiList.isEmpty()) {
            new AlertDialog.Builder(mContext)
                    .setTitle(R.string.clear_title)
                    .setMessage(R.string.clear_warning_tip)
                    .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            mImsiList.clear();
                            MainActivity.getInstance().getWarningImsiList().clear();
                            PrefUtil.build().putString("warning_list", GsonUtil.createJsonString(MainActivity.getInstance().getWarningImsiList()));
                            mImsiAdapter.resetShowData();
                        }
                    })
                    .setNegativeButton(R.string.cancel, null)
                    .show();
        }else if (this.isAdded()) MainActivity.getInstance().showToast(getString(R.string.list_empty));
    }

    ActivityResultLauncher<Intent> activityForResult = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            AppLog.I("SettingFragment onActivityResult result = " + result);
            if (result.getResultCode() == Activity.RESULT_OK) {
                if (result.getData() != null) {
                    AppLog.I("SettingFragment onActivityResult result.getData().getDataString() = " + result.getData().getDataString());
                    String dataString = result.getData().getDataString();
                    if (dataString != null && !dataString.isEmpty()) {
                        String[] split = dataString.split("%");
                        StringBuilder path = new StringBuilder(FileUtil.build().getSDPath());
                        for (int i = 1; i < split.length; i++) {
                            path.append("/");
                            path.append(split[i].substring(2));
                        }

                        //path.deleteCharAt(path.length() - 1);
                        final ProgressDialog progressDialog = new ProgressDialog(mContext, R.style.ThemeProgressDialogStyle);
                        progressDialog.setCanceledOnTouchOutside(false);
                        progressDialog.setCancelable(false);   // 返回键不消失
                        progressDialog.setTitle("正在读取");
                        String message = "正在打开文件";
                        progressDialog.setMessage(message);
                        progressDialog.show();

                        ExcelUtil.readExcel(path.toString(), new ExcelUtil.OnReadProgressListener() {
                            @Override
                            public void onReadProgress(int position) {
                                String message = "当前进度： " + position + "%";
                                MainActivity.getInstance().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        progressDialog.setMessage(message);
                                    }
                                });
                            }

                            @Override
                            public void onReadOk(HashSet<MyUeidBean> set, int allCount, int okCount, int errCount, int reCount) {
                                String message = "读取完成，正在解析";
                                MainActivity.getInstance().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        progressDialog.setMessage(message);
                                        progressDialog.dismiss();
                                    }
                                });
                                parseReadList(set, allCount, okCount, errCount, reCount);
                            }

                            @Override
                            public void onReadFail(String err) {
                                ExcelUtil.readExcel(mContext, result.getData().getData(), new ExcelUtil.OnReadProgressListener() {
                                    @Override
                                    public void onReadProgress(int position) {
                                        String message = "当前进度： " + position + "%";
                                        MainActivity.getInstance().runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                progressDialog.setMessage(message);
                                            }
                                        });
                                    }

                                    @Override
                                    public void onReadOk(HashSet<MyUeidBean> set, int allCount, int okCount, int errCount, int reCount) {
                                        String message = "读取完成，正在解析";
                                        MainActivity.getInstance().runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                progressDialog.setMessage(message);
                                                progressDialog.dismiss();
                                            }
                                        });
                                        parseReadList(set, allCount, okCount, errCount, reCount);
                                    }

                                    @Override
                                    public void onReadFail(String err) {
                                        MainActivity.getInstance().runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                MainActivity.getInstance().showToast("数据格式不符合规范，请检查!");
                                            }
                                        });
                                    }
                                });
                            }
                        });
                    }
                }
            } else if (result.getResultCode() == Activity.RESULT_CANCELED) {
                //MainActivity.getInstance().showToast("您未选择文件!");
            }
        }
    });

    private void parseReadList(HashSet<MyUeidBean> set, int allCount, int okCount, int errCount, int reCount){
        for (MyUeidBean bean : set) {
            MainActivity.getInstance().addWarningList(bean.getName(), bean.getUeidBean().getImsi());
        }
        StringBuilder sb = new StringBuilder();

        sb.append(getString(R.string.import_all_count)).append("\t").append(allCount).append("\n");
        sb.append(getString(R.string.import_err_count)).append("\t").append(errCount).append("\n");
        sb.append(getString(R.string.import_repeat_count)).append("\t").append(reCount).append("\n");
        sb.append(getString(R.string.import_success_count)).append("\t").append(okCount).append("\n");
        MainActivity.getInstance().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mImsiAdapter.notifyDataSetChanged();
                MainActivity.getInstance().showRemindDialog(getString(R.string.import_result), sb.toString());
            }
        });

        if (okCount > 0)
            PrefUtil.build().putString("warning_list", GsonUtil.createJsonString(MainActivity.getInstance().getWarningImsiList()));
    }

    private void showBlackListCfgDialog(final boolean isAdd, ImsiBean bean) {

        Dialog dialog = MainActivity.getInstance().createDialog(false);

        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_black_list_cfg, null);

        TextView tv_black_cfg_title = view.findViewById(R.id.tv_black_cfg_title);

        final TextView btn_ok = view.findViewById(R.id.btn_ok);
        final TextView btn_cancel = view.findViewById(R.id.btn_cancel);
        TextView back = view.findViewById(R.id.back);
        final EditText ed_imsi_name = view.findViewById(R.id.ed_imsi_name);
        final AutoCompleteTextView actv_imsi = view.findViewById(R.id.actv_imsi);

        if (isAdd) {
            tv_black_cfg_title.setText(R.string.add_black_title);
            btn_ok.setText(R.string.add);
            btn_cancel.setText(R.string.cancel);
            btn_cancel.setTextColor(Color.parseColor("#666666"));
            back.setVisibility(View.GONE);
        } else {
            tv_black_cfg_title.setText(R.string.edit_black_title);
            btn_ok.setText(R.string.confirm_modify);
            btn_cancel.setText(R.string.delete);
            btn_cancel.setTextColor(Color.RED);
            back.setVisibility(View.VISIBLE);
            if (bean != null) {
                ed_imsi_name.setText(bean.getNotes());
                actv_imsi.setText(bean.getImsi());
            }
        }

        btn_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String imsi_name = ed_imsi_name.getText().toString();
                String imsi = actv_imsi.getText().toString();
                if (imsi_name.isEmpty() || imsi.isEmpty()) {
                    MainActivity.getInstance().showToast(getString(R.string.data_empty_tip));
                    return;
                }
                if (imsi.length() != 15) {
                    MainActivity.getInstance().showToast(getString(R.string.imsi_err_tip));
                    return;
                }

                if (isAdd) {
                    if (!MainActivity.getInstance().addWarningList(imsi_name, imsi)) {
                        MainActivity.getInstance().showToast(getString(R.string.imsi_repeat_tip));
                        return;
                    }
                    refreshListView();
                } else {
                    MainActivity.getInstance().addWarningList(imsi_name, imsi);
                    refreshListView();
                    MainActivity.getInstance().showToast(getString(R.string.update_ok));
                }
                PrefUtil.build().putString("warning_list", GsonUtil.createJsonString(MainActivity.getInstance().getWarningImsiList()));
                MainActivity.getInstance().closeDialog(dialog);
            }
        });
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (btn_cancel.getText().toString().equals(getString(R.string.delete))) {
                    new AlertDialog.Builder(mContext)
                            .setTitle(R.string.delete_tip_title)
                            .setMessage(R.string.delete_tip)
                            .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int type) {
                                    List<ImsiBean> warningImsiList = MainActivity.getInstance().getWarningImsiList();
                                    for (int i = 0; i < warningImsiList.size(); i++) {
                                        if (warningImsiList.get(i).getImsi().equals(bean.getImsi())){
                                            MainActivity.getInstance().getWarningImsiList().remove(i);

                                            PrefUtil.build().putString("warning_list", GsonUtil.createJsonString(MainActivity.getInstance().getWarningImsiList()));
                                            refreshListView();
                                            break;
                                        }
                                    }

                                    MainActivity.getInstance().closeDialog(dialog);
                                }
                            })
                            .setNegativeButton(R.string.cancel, null)
                            .show();
                } else MainActivity.getInstance().closeDialog(dialog);
            }
        });
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MainActivity.getInstance().closeDialog(dialog);
            }
        });
        MainActivity.getInstance().showDialog(dialog, view, false);
    }
}